/**
 * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation; either version 2.1 of the License, or (at your option)
 * any later version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 * details.
 */

package com.liferay.analystest.util;

import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.file.*;
import java.util.List;

/**
 * Extract file from specified zip file.
 *
 * @author Dante Wang
 */
public class ZipUtil {

	public static String extract(String target, Path zipFile)
		throws Exception {

		return extract(target, zipFile, null);
	}

	public static String extract(
			String target, Path zipFile, Charset charset)
		throws Exception {

		charset = charset == null ? Charset.defaultCharset() : charset;

		String content = null;

		try (
			FileSystem zfs =
				FileSystems.newFileSystem(zipFile, null)) {

			byte[] byteContent = Files.readAllBytes(zfs.getPath(target));

			content =
				String.valueOf(charset.decode(ByteBuffer.wrap(byteContent)));
		}

		return content;
	}

	public static List<String> extractLines(String target, Path zipFile)
		throws Exception {

		return extractLines(target, zipFile, null);
	}

	public static List<String> extractLines(
			String target, Path zipFile, Charset charset)
		throws Exception {

		charset = charset == null ? Charset.defaultCharset() : charset;

		List<String> content = null;

		try (
			FileSystem zfs =
				FileSystems.newFileSystem(zipFile, null)) {

			content = Files.readAllLines(zfs.getPath(target), charset);
		}

		return content;
	}

}